package ua.com.infinite.mobile.adapters;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import ua.com.infinite.mobile.R;
import ua.com.infinite.mobile.pageindicator.IconPagerAdapter;
import ua.com.infinite.mobile.slidingmenu.fragments.TagsConst;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;

public class PageAdapter extends FragmentStatePagerAdapter implements IconPagerAdapter{
	private ArrayList<String> titles = new ArrayList<String>();
	private ArrayList<Fragment> fragments = new ArrayList<Fragment>();
	private ViewPager viewPager;
	private Context context;
	private int currentPosition = 0;
	
	private int mCount = fragments.size();

	public PageAdapter(Context context, FragmentManager fm, ViewPager vp) {
		super(fm);
		this.context = context;
		viewPager = vp;
		viewPager.setAdapter(this);
		
	}
	
	public ArrayList<String> createTitles(){
		this.titles.clear();
		for (Fragment fragment : fragments) {
			String title = getNameByTag(fragment.getArguments().getString("tag"));
			titles.add(title);
		}
		
		return titles;
	}

	public void addTab(Fragment frag) {
		fragments.add(frag);
		titles = createTitles();
		notifyDataSetChanged();
		
	}
	
	public void clear(){
		fragments.clear();
	}

	@Override
	public Fragment getItem(int position) {
		return fragments.get(position);
	}

	@Override
	public int getCount() {
		return fragments.size();
	}
	
	public int getCurrentPosition(){
		return currentPosition;
	}
	
	@Override
    public CharSequence getPageTitle(int position) {
 
		return titles.get(position % titles.size()); 
    }

	@Override
	public int getIconResId(int index) {
		
		return 0;
	}
	
	@Override
	public void destroyItem(View container, int position, Object object) {
	    //super.destroyItem(container, position, object);
	    fragments.remove(position);
	}
	
	private String getNameByTag(String tag){
		if(tag.equals(TagsConst.TAG_ALL)){
			return context.getResources().getString(R.string.all_news);
		}
		if(tag.equals(TagsConst.TAG_PARTNER)){
			return context.getResources().getString(R.string.partner_news);
		}
		if(tag.equals(TagsConst.TAG_TRANSAKTIONS)){
			return context.getResources().getString(R.string.transaktions);
		}
		return tag;
	}

	
}
